package com.rfs.thread;

import java.text.SimpleDateFormat;

/**
 * @author renfushuai
 * @date 2022/2/18
 */
public class ThreadLocalTest {
    static class User {
        private Integer id;
    }
/*
* 用ThreadLocal作为容器，当每个线程访问这个 ThreadLocal会为每个线程提供一份变量，各个线程互不影响。
* withInitial。这个方法采用Lambda方式传入实现了 Supplier 函数接口的参数
* SimpleDateFormat重写了hashCode方法调用pattern.hashCode(); 所以每个线程都是都拥有相同的对象
*
* */
    static ThreadLocal<SimpleDateFormat> tl = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
    static ThreadLocal<User> userTl = ThreadLocal.withInitial(() -> new User());

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            System.out.println("SimpleDateFormat---线程id:" + Thread.currentThread().getId() + ",对象地址:" + tl.get());
            System.out.println("UserDto---线程id:" + Thread.currentThread().getId() + ",对象地址:" + userTl.get());
        }, "t1");

        Thread t2 = new Thread(() -> {
            System.out.println("SimpleDateFormat---线程id:" + Thread.currentThread().getId() + ",对象地址:" + tl.get());
            System.out.println("UserDto---线程id:" + Thread.currentThread().getId() + ",对象地址:" + userTl.get());
        }, "t2");
        t1.start();
        t2.start();
       /* ExecutorService executorService = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 20; i++) {
            executorService.execute(()->{
                System.out.println("SimpleDateFormat---线程id:"+Thread.currentThread().getId()+",对象地址:"+tl.get());
                System.out.println("UserDto---线程id:"+Thread.currentThread().getId()+",对象地址:"+userTl.get().hashCode());
            });
        }
        executorService.shutdown();*/
       /* for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println("SimpleDateFormat---线程id:"+Thread.currentThread().getId()+",对象地址:"+tl.get());
                System.out.println("UserDto---线程id:"+Thread.currentThread().getId()+",对象地址:"+userTl.get().hashCode());
            }).start();
        }*/
    }
}
